var app = getApp();
var util = require("../../utils/util.js");
var siteinfo = require('../../siteinfo.js');
Page({
  data: {
    isSign:false,//是否签名
    loginModal: false,
    isLogin: true, //是否登录
    name: '',
    idCard: '',
    schoolName: '',
    mobile:'',
    state: '', //（0待审核，1待缴费，2未通过，3已分配，4已缴费，9已删除
    OrgName:'',//工作单位
	unitPhone:'',//单位联系电话
	postName:'',//岗位名称
    index:0,
    orgId: '',
    phoneNum:'',
    // mobile: '',//电话号码
    certificateNo:'',//毕业证书编号
    levelNum:'',//原证书编号
    address:'',//邮寄地址
    declarationPeriod:'',//累计从事申报职业年限
    images: '/image/touxiang.png',
	imagesFront: '/image/idFront.png',
	imagesReverse: '/image/idReverse.png',
	imagesXueli: '/image/addPic.png',
	imagesWork: '/image/addPic.png',
	kemu:[],
	
	recordCertificate:'', //学历证书 
	workProve:'', //工作证明
	idFront:'', //身份证正面
	idReverse:'', //身份证反面
	
    typeList: [{
      id:'',
      name: '请选择考生类型'
    }, {
      id: 0,
        name: '在校考生'
    }, {
      id: 1,
        name: '社会考生'
    }],
  genre:[{
    id: null,
    name: '请选择认定类型'
  },
  {
    id: 0,
    name: '正考'
  },
  {
    id: 1,
    name: '补考'
  }],
  index: 0,
  sexList: [{
    id: 0,
    name: '请选择性别'
  }, {
    id: 1,
    name: '男'
  }, {
    id: 2,
    name: '女'
  }],
  indexSex: 0,
  educationList: ["请选择学历", '初中', '高中', '中专', '大专', '大学'], //学历
  indexEducation: 0,
  indexProfile: 0,
  birthTime: '',
  education:'', //学历
  workDate:'',
  //experience:'',
  // dateWork:'',//参加工作时间
  classLevel:'',//原职业等级
  indexKpoints: 0,
  alreadyModal: false,
  gradeList: ["请选择类型",'三级', '四级', '五级'], 
  nationList: ["请选择类型", "正考", "补考"],
  professionList: ["请选择类型",'育婴员', '保育师', '养老护理员'], 
  indexNation: 0,
  indexDeclarationLevel:0,
  indexProfession:0,
  isProfession: false,
  isNation: false,
  isDeclarationLevel: false,
  isEducation: false,
  declarationLevel:'',//申报认定等级
  profession:'',//申报认定职业
  region: [],
  newsList:[],
    typeIndex:0,
    type:'',
    inputShowed: false,
    inputVal: "",
    a:true ,//选中机构后取消下拉框
    list:[ {id:0,name: '理论'},
    {id:1,name: '实操'}
]
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },

  onLoad: function(options) {
    this.setData({
      id: options.id, //认证批次id
      grade:wx.getStorageSync('certificateInfo').grade
    })
    this.getUserDetail()
    // this.selCertificateFill()
    // this.getProfileFillList()
    var time = util.formatTime(new Date());
    this.setData({
      nowDate: time.substring(0, 10),
    })
    //this.getUserDetail()
    // this.selMyCer()
  },
  onShow: function() {
    var _this = this
    //获取签名路径
    if(wx.getStorageSync('signSrc')!=null){
      _this.setData({
        signSrc: wx.getStorageSync('signSrc'),
        isSign:true
      })
    }
    if (app.globalData.btn) {
      _this.getUserDetail()
      // _this.selCertificateFill()
      app.globalData.btn = false
      
    }
    _this.getUserisSignUp()
  },
  getDeclarationPeriod:function(e){//累计从事申报职业年限
    this.setData({
      declarationPeriod:e.detail.value
    })
  },
    //获取姓名
    getName: function (e) {
      var value = e.detail.value;
      this.setData({
        name: value
      });
    },
      //选择性别
  sexChange: function(e) {
    this.setData({
      indexSex: e.detail.value
    })
  },
  //选择出生年月
  bindDateChange: function(e) {
    this.setData({
      birthTime: e.detail.value
    })
  },
  //参加工作时间
  bindDateChanges: function(e) {
    this.setData({
      workDate: e.detail.value
    })
  },
  //选择民族
  nationChange: function(e) {
    var _this = this
    _this.setData({
      indexNation: e.detail.value,
      nation: _this.data.nationList[e.detail.value]
    })
  },
  //申报认定等级
  declarationLevelChange: function(e) {
	  var _this = this
	  _this.setData({
	    indexDeclarationLevel: e.detail.value,
	    declarationLevel: _this.data.gradeList[e.detail.value]
	  })
  },
  //申报认定职业
  professionChange: function(e) {
    var _this = this
    _this.setData({
      indexProfession: e.detail.value,
      profession: _this.data.professionList[e.detail.value]
    })
  },
  //选择学历
  educationChange: function(e) {
    var _this = this
    _this.setData({
      indexEducation: e.detail.value,
      education: _this.data.educationList[e.detail.value]
    })
  },
  //获取专业
  // getMajor:function(e){
  //   this.setData({
  //     major:e.detail.value
  //   });
  // },
  //获取毕业证书编号
  getCertificateNo:function(e){
    this.setData({
      certificateNo:e.detail.value
    });
  },
  //工作单位名称
  getOrgName:function(e){
    this.setData({
      orgName:e.detail.value
    })
  },
  //单位联系电话
  getUnitPhone:function(e){
    this.setData({
      unitPhone:e.detail.value
    })
  },
  //岗位名称
  getPostName:function(e){
    this.setData({
      postName:e.detail.value
    })
  },
  getClassLevel:function(e){
    this.setData({
      classLevel:e.detail.value
    })
  },
  //获取原证书编号
  getLevelNum:function(e){
    this.setData({
      levelNum:e.detail.value
    })
  },
  //获取身份证号
  getIdNumber:function(e){
    this.setData({
      idNumber:e.detail.value
    })
  },
  //获取手机号
  getMobile:function(e){
    this.setData({
      mobile:e.detail.value
    })
  },
  //获取邮寄地址
  getAddress:function(e){
    this.setData({
      address:e.detail.value
    })
  },
  //获取学习、工作经历
 //  getExperience:function(e){
 //    this.setData({
 //      experience:e.detail.value
 //    })
	// console.log(this.data.experience)
 //  },
  //选择省市区
  bindRegionChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  //认定科目
  checkboxChange: function(e) {
    console.log(e.detail.value)
	this.setData({
	  kemu: e.detail.value
	})
  },
  //选择考生类型
  changeType: function (e) {
    var _this = this
    _this.setData({
      typeIndex: e.detail.value,
      type: _this.data.typeList[e.detail.value].id
    })
  },
  getUserisSignUp:function(){
      app._getLogin(siteinfo.selUserIsSignUp,{cbatch:wx.getStorageSync('certificateInfo').authentication_id},function(res){
        if(res.data.isSignUp){
          wx.navigateTo({
            url: '/pages/signExamine/signExamine?id='+res.data.signUpId,
          })
        }
      })
  },
  //获取用户照片
  getUserDetail: function () {
    var _this = this;
    app._getLogin(siteinfo.selUserDetail, {}, function (result) {
      if (result.data.headPortrait != '' && result.data.headPortrait != null) {
        _this.setData({
          images: result.data.headPortrait
        });
      }
      _this.setData({
        photo: result.data.headPortrait,
      });
    });

  },
  chooseImageFront(e) { //身份证正面
    var _this = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (res.tempFiles[0].size < 5242880) {
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success(result) {
              const tempFilePaths = res.tempFilePaths
              app._uploadFile(siteinfo.fileImprot,
                res.tempFiles[0].path,
                'file', {
                  name: res.tempFiles[0].name
                },
                function (res1) {
                  _this.setData({
                    idFront: res1.data,
                    imagesFront: tempFilePaths,
                  })
                })
            }
          })
        } else {
          app.showError('寸照应小于5M！')
        }
      }
    })
  },
  chooseImageReverse(e) { //身份证反面
    var _this = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (res.tempFiles[0].size < 5242880) {
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success(result) {
              const tempFilePaths = res.tempFilePaths
              app._uploadFile(siteinfo.fileImprot,
                res.tempFiles[0].path,
                'file', {
                  name: res.tempFiles[0].name
                },
                function (res1) {
                  _this.setData({
                    idReverse: res1.data,
                    imagesReverse: tempFilePaths,
                  })
                })
            }
          })
        } else {
          app.showError('寸照应小于5M！')
        }
      }
    })
  },
  chooseImageXueli(e) { //学历证书
    var _this = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (res.tempFiles[0].size < 5242880) {
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success(result) {
              const tempFilePaths = res.tempFilePaths
              app._uploadFile(siteinfo.fileImprot,
                res.tempFiles[0].path,
                'file', {
                  name: res.tempFiles[0].name
                },
                function (res1) {
                  _this.setData({
                    recordCertificate: res1.data,
                    imagesXueli: tempFilePaths,
                  })
                })
            }
          })
        } else {
          app.showError('寸照应小于5M！')
        }
      }
    })
  },
  chooseImageWork(e) { //工作证明
    var _this = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (res.tempFiles[0].size < 5242880) {
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success(result) {
              const tempFilePaths = res.tempFilePaths
              app._uploadFile(siteinfo.fileImprot,
                res.tempFiles[0].path,
                'file', {
                  name: res.tempFiles[0].name
                },
                function (res1) {
                  _this.setData({
                    workProve: res1.data,
                    imagesWork: tempFilePaths,
                  })
                })
            }
          })
        } else {
          app.showError('寸照应小于5M！')
        }
      }
    })
  },
  chooseImage(e) {
    var _this = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (res.tempFiles[0].size < 5242880) {
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success(result) {
              const tempFilePaths = res.tempFilePaths
              app._uploadFile(siteinfo.fileImprot,
                res.tempFiles[0].path,
                'file', {
                  name: res.tempFiles[0].name
                },
                function (res1) {
                  _this.setData({
                    photo: res1.data,
                    images: tempFilePaths,
                  })
                })
            }
          })
        } else {
          app.showError('寸照应小于5M！')
        }
      }
    })
  },



  
  // 表单提交
  formSubmit: function(e) {
    var _this = this,
    values = e.detail.value;
    values.sex = _this.data.sexList[_this.data.indexSex].name //性别
    values.birthTime = _this.data.birthTime //出生日期
    values.workDate = _this.data.workDate //工作时间
	//values.experience = _this.data.experience
    values.fileUrl = _this.data.fileUrl
    values.mobile=_this.data.mobile
    // 表单验证
    if (!_this.validation(values)) {
      app.showError(_this.data.error);
      return false;
    }
    //先上传签名图片再提交表单
    app._uploadFile(siteinfo.fileImprot,
      wx.getStorageSync('signSrc'),
      'file', {
        name: app.getUserId()+"签名.png"
      },
      function(res) {
        app._post_form(siteinfo.addCertificateFill, {
          cognizanceSubject:values.course,
          birthTime: values.birthTime,
          workDate: values.workDate,
          declarationPeriod:values.declarationPeriod,
          education: _this.data.education,
          cognizanceType: _this.data.nation,
          declarationLevel: _this.data.declarationLevel, //申报认定等级
          //experience: values.experience,
          imgUrl: _this.data.photo,
		  
		  idFront:_this.data.idFront, //身份证正面
		  idReverse:_this.data.idReverse, //身份证反面
		  recordCertificate:_this.data.recordCertificate, //学历证书
		  workProve:_this.data.workProve, //工作证明
		  
          idNumber: values.idNumber,
          phone:values.mobile,
          certificateNo:values.certificateNo,
          address:_this.data.address,
          //major: values.major,
          name: values.name,
          declaration:_this.data.profession,
          unitName: values.orgName,
		  unitPhone: values.unitPhone,
		  postName: values.postName,
          profileId: values.profileId,
          sex: values.sex,
          occupationLevel:values.classLevel,
          originalCertificateNo:values.levelNum,
          promiseExplain: null,
          signSrc:res.data,
          authenticationId:wx.getStorageSync('certificateInfo').authentication_id
        },
        function(res) {
          //console.log("res",res)
          if (res.code == "40013" || res.code == 40013) {
            wx.showModal({
              title: '友情提示',
              content: res.msg + '，可查看申请信息',
              confirmText: '去查看',
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/signExamine/signExamine?id='+res.data,
                  })
                }
              }
            })
          } else {
            var isOpenId = wx.getStorageSync('isOpenId')
            if (isOpenId) {
              if (isOpenId == true) {
                app.subscribeMessage(res.msg)
              }
            }
            wx.showModal({
              title: '友情提示',
              content: '提交成功，请等待审核，可在个人中心—我的报名中查看进度',
              showCancel: false,
              confirmText: '去查看',
              success: function(result) {
                if (result.confirm) {
                  wx.redirectTo({
                    url: '/pages/signExamine/signExamine?id='+res.data,
                  })
                }
              }
            })
          }
        }
      );
      }
    )

  },
  /**
   * 表单验证
   */
  validation: function(values) {
    var _this = this
    if ('' == values.name) {
      this.data.error = '姓名不能为空';
      return false;
    }
    if ('请选择性别' == values.sex) {
      this.data.error = '性别不能为空';
      return false;
    }
    if ('' == values.birthTime || null == values.birthTime) {
      this.data.error = '出生日期不能为空';
      return false;
    }
	if ('' == _this.data.education) {
	  this.data.error = '学历不能为空';
	  return false;
	}
    if ('' == values.workDate || null == values.workDate) {
      this.data.error = '参加工作时间不能为空';
      return false;
    }
    if ('' == values.declarationPeriod || null == values.declarationPeriod) {
      this.data.error = '累计从事申报职业年限不能为空';
      return false;
    }
	if ('' == values.orgName) {
	  this.data.error = '工作单位名称不能为空';
	  return false;
	}
    if ('' == values.unitPhone) {
      this.data.error = '单位联系电话不能为空';
      return false;
    }
	if ('' == values.postName) {
	  this.data.error = '岗位名称不能为空';
	  return false;
	}
    if ('' == values.idNumber) {
      this.data.error = '身份证号不能为空';
      return false;
    }
    if ('' != values.idNumber) {
      if (!util.cardId().checkIdCardNo(values.idNumber.trim())) { 
        this.data.error = '请输入正确的身份证号';
        return false;
      } 
    }
	if ('' == values.mobile) {
	  this.data.error = '手机号不能为空';
	  return false;
	}
	var phone = util.regexConfig().phone;
	if (!phone.test(values.mobile)) {
	  this.data.error = '手机号不符合要求';
	  return false;
	}
	if ('' == _this.data.declarationLevel) {
	  this.data.error = '申报认定等级不能为空';
	  return false;
	}
	if ('' == _this.data.profession) {
	  this.data.error = '申报认定职业不能为空';
	  return false;
	}
	
	// if ('' == _this.data.experience) {
	//   _this.data.error = '学习、工作经历不能为空';
	//   return false;
	// }
	// if(_this.data.kemu.length==0){
	//   this.data.error = '认定科目不能为空';
	//   return false;
	// }
    if(!_this.data.isSign){
      app.showError('未签名！');
      return false;
    }
    if ('/image/s.png' == _this.data.photo || '' == _this.data.photo) {
      this.data.error = '寸照不能为空';
      return false;
      }
	if ('' == _this.data.idFront) {
		 this.data.error = '身份证正面照不能为空';
	  return false;
	  }
	if ('' == _this.data.idReverse) {
		this.data.error = '身份证反面照不能为空';
	  return false;
	  }
  //   if ('' == _this.data.recordCertificate) {
		// this.data.error = '学历证书不能为空';
		// return false;
	 // }
	 if ('' == _this.data.workProve) {
		this.data.error = '工作证明不能为空';
	 	return false;
	  }
    return true;
  },

  //选择要上传的上传文件
  chooseFile() {
    let _this = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        // console.log(" :res", res.tempFiles[0])
        _this.setData({
          fileName: res.tempFiles[0].name,
        })
        app._uploadFile(siteinfo.fileImprot,
          res.tempFiles[0].path,
          'file', {
            name: res.tempFiles[0].name
          },
          function(res) {
            //  console.log("res", res.data)
            _this.setData({
              fileUrl: res.data,
            })
          }
        )
      }
    })
  },
  signName:function(){
    wx.navigateTo({
      url: 'signName',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})